package com.socket;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import sun.nio.ch.IOUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {

    public static void main(String[] args) throws IOException {
        // 开始监听端口
        ServerSocket serverSocket = new ServerSocket(55511);
        while (true){
            try {
                Console.log("server is lister in port:{}", serverSocket.getLocalPort());
                // 该方法会阻塞, 知道有客户端来访问服务端, 然后该方法返回一个socket套接字
                // 如果像本demo一样, 对socket做同步处理, 那做此期间, 服务端不会响应其他客户端, 也就是服务端只能一对一处理.
                // 所以正确对方式是对此处对套接字做异步处理, 但本demo就不增加复杂度了.
                Socket client = serverSocket.accept();
                String msg = null;
                // 获取socket的输入输出流
                InputStream in = client.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                OutputStream out = client.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(out));
                //
                while((msg = bufferedReader.readLine()) != null){
                    System.out.println("read msg: " + msg);
                    bufferedWriter.write("server ack");
                    bufferedWriter.write("\n");
                    bufferedWriter.flush();
                }
                System.out.println(msg);
                client.shutdownInput();
                client.shutdownOutput();
                IoUtil.close(client);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
